<?php
/**
 *  标签解析引擎模型
 */
namespace app\home\model;
use think\Model;
use think\Db;
class ContentModel extends Model
{

    // 存储分类及子编码
    protected $scodes = array();

    // 存储分类查询数据
    protected $sorts;

    // 存储栏目位置
    protected $position = array();

    // 上一篇
    protected $pre;

    // 下一篇
    protected $next;

    // 获取模型数据
    public function checkModelUrlname($urlname)
    {
        return Db::name('model')->where("urlname='$urlname'")->find();
    }

	// 站点配置信息
    public function getSite()
    {
        return Db::name('site')->where("acode='" . get_lg() . "'")->find();
    }

    // 公司信息
    public function getCompany()
    {
        return Db::name('company')->where("acode='" . get_lg() . "'")->find();
    }

    // 自定义标签
    public function getLabel()
    {
        return Db::name('label')->decode()->column('value,type', 'name');
    }

    // 单个分类信息，不区分语言，兼容跨语言
    public function getSort($scode)
    {
        $field = array(
            'a.*',
            'c.name AS parentname',
            'b.type',
            'b.urlname'
        );
        $join = array(
            array(
                'ay_model b',
                'a.mcode=b.mcode',
                'LEFT'
            ),
            array(
                'cb_content_sort c',
                'a.pcode=c.scode',
                'LEFT'
            )
        );
        return Db::name('content_sort a')->field($field)
            ->where("a.scode='$scode' OR a.filename='$scode'")
            ->join($join)
            ->find();
    }

    // 多个分类信息
    public function getMultSort($scodes)
    {
        $field = array(
            'a.*',
            'c.name AS parentname',
            'b.type',
            'b.urlname'
        );
        $join = array(
            array(
                'ay_model b',
                'a.mcode=b.mcode',
                'LEFT'
            ),
            array(
                'cb_content_sort c',
                'a.pcode=c.scode',
                'LEFT'
            )
        );
        return Db::name('content_sort a')->field($field)
            ->where("a.acode='" . get_lg() . "'")
            ->in('a.scode', $scodes)
            ->join($join)
            ->order('a.sorting,a.id')
            ->select();
    }
    // 指定分类数量
    public function getSortRows($scode)
    {
        $this->scodes = array(); // 先清空

        // 获取多分类子类
        $arr = explode(',', $scode);
        foreach ($arr as $value) {
            $scodes = $this->getSubScodes(trim($value));
        }

        // 拼接条件
        $where1 = array(
            "scode in (" . implode_quot(',', $scodes) . ")",
            "subscode='$scode'"
        );
        $where2 = array(
            "acode='" . get_lg() . "'",
            'status=1',
            "date<'" . date('Y-m-d H:i:s') . "'"
        );

        $result = Db::name('content')->where($where1, 'OR')
            ->where($where2)
            ->column('id');
        return count($result);
    }

    // 分类栏目列表关系树
    public function getSortsTree()
    {
        $fields = array(
            'a.*',
            'b.type',
            'b.urlname'
        );
        $join = array(
            'ay_model b',
            'a.mcode=b.mcode',
            'LEFT'
        );
        $result = Db::name('content_sort a')->where("a.acode='" . get_lg() . "'")
            ->where('a.status=1')
            ->join($join)
            ->order('a.pcode,a.sorting,a.id')
            ->column($fields, 'scode');

        foreach ($result as $key => $value) {
            if ($value['pcode']) {
                $result[$value['pcode']]['son'][] = $value; // 记录到关系树
            } else {
                $data['top'][] = $value; // 记录顶级菜单
            }
        }
        $data['tree'] = $result;
        return $data;
    }

    // 获取分类名称
    public function getSortName($scode)
    {
        $result = $this->getSortList_qd();
        return $result[$scode]['name'];
    }

    // 分类顶级编码
    public function getSortTopScode($scode)
    {
        $result = $this->getSortList_qd();
        return $this->getTopParent($scode, $result);
    }

    // 获取位置
    public function getPosition($scode)
    {
		$result = $this->getSortList_qd();
		$this->position = array();// 重置
		$this->getTopParent($scode, $result);
        return array_reverse($this->position);
    }
    // 分类顶级编码
    private function getTopParent($scode, $sorts)
    {
        if (! $scode || ! $sorts) {
            return;
        }
        $this->position[] = $sorts[$scode];
        if ($sorts[$scode]['pcode']) {
            return $this->getTopParent($sorts[$scode]['pcode'], $sorts);
        } else {
            return $sorts[$scode]['scode'];
        }
    }

    // 分类子类集
    public function getSubScodes($scode)
    {
        if (! $scode) {
            return;
        }
        $this->scodes[] = $scode;
        $subs = Db::name('content_sort')->where("pcode='$scode'")->column('scode');
        if ($subs) {
            foreach ($subs as $value) {
                $this->getSubScodes($value);
            }
        }
        return $this->scodes;
    }

	//查询子栏目
	public function getSonScodes($scode,$limit=10)
    {
			if (! $scode) {
				return;
			}
			$fields = array(
				'a.id',
				'a.pcode',
				'a.scode',
				'a.name',
				'a.filename',
				'a.outlink',
				'a.ico',
				'a.subname',
				'b.type',
				'b.urlname'
			);
			$Order=" a.sorting asc,a.id asc";
			$subs = Db::name('content_sort a')
				->field($fields)
				->where('a.pcode ='.$scode)
				->join('model b', 'a.mcode=b.mcode', 'left')
				->order($Order)
				->limit($limit)
				->select();

			foreach($subs as $key=>$val) {
				if($val['type']!=1){
					$subs[$key]['link']=url($val['urlname'].'list',['tid'=>$val['scode']]);
				}else{
					$subs[$key]['link']=url($val['urlname'],['tid'=>$val['scode']]);
				}
			}
			return $subs;
	}

    // 获取栏目清单
    public function getSortList($pcode=0,$limit=10)
    {
        if (! isset($sorts)) {
            $fields = array(
                'a.id',
                'a.pcode',
                'a.scode',
                'a.name',
                'a.filename',
                'a.outlink',
				'b.type',
                'b.urlname'
            );
			$Order=" a.sorting asc,a.id asc";
            $sorts = Db::name('content_sort a')
				->field($fields)
				->where('a.status = 1')
				->join('model b', 'a.mcode=b.mcode', 'left')
				->where('a.pcode = '.$pcode.'')
				->order($Order)
				->limit($limit)
				->select();
        }
		foreach($sorts as $key=>$val) {
			if($val['type']!=1){
				$sorts[$key]['link']=url($val['urlname'].'list',['tid'=>$val['scode']]);
			}else{
				$sorts[$key]['link']=url($val['urlname'],['tid'=>$val['scode']]);
			}
		}
        return $sorts;
    }

	// 获取栏目清单ID
    public function getSortList_qd()
    {
		$fields = array(
                'a.id',
                'a.pcode',
                'a.scode',
				'a.ico',
				'a.pic',
                'a.name',
                'a.filename',
                'a.outlink',
                'b.type',
                'b.urlname'
            );
        if (! isset($this->sorts)) {
            $this->sorts = Db::name('content_sort a')
                ->join('model b', 'a.mcode=b.mcode', 'left')
                ->column('a.id,a.pcode,a.scode,a.name,a.outlink,a.filename,a.ico,a.pic,b.type,b.urlname', 'scode');
        }
        return $this->sorts;
    }

    // 获取筛选字段数据
    public function getSelect($field)
    {
        return Db::name('extfield')->where("name='$field'")->value('value');
    }

    // 列表内容,带分页，不区分语言，兼容跨语言
    public function getLists($scode, $num=20, $order='a.id desc',$other='', $run1=0, $run2=0, $run3=0,$tags= array())
    {
		$UrlParam['tid']=$scode;
        $fields = array(
            'a.*',
            'b.name as sortname',
            'b.filename as sortfilename',
            'c.name as subsortname',
            'c.filename as subfilename',
            'd.type',
            'd.name as modelname',
            'd.urlname',
            'e.*'
        );
        $scode_arr = array();
        if ($scode) {
            // 获取所有子类分类编码
            //$this->scodes = array(); // 先清空
            $arr = explode(',', $scode); // 传递有多个分类时进行遍历
            foreach ($arr as $value) {
                $scodes = $this->getSubScodes(trim($value));
            }
            // 拼接条件
			if($scodes){
				$scode_arr = "a.scode in (" . implode_quot(',', $scodes) . ")";
			}else{
				$scode_arr = "a.subscode=".$scode."";
			}
        }
		//$where['a.status'] =1;
        if(!empty($other)){
			$scode_arr.= " and ".$other;
		}
		 
		if($run1){
			$scode_arr.=' and a.rund1 = '.$run1.'';
		}
		
		if($run2){
			$scode_arr.=' and a.rund2 = '.$run2.'';
		}
		if($run3){
			$scode_arr.=' and a.rund3 = '.$run3.'';
		}
        // 筛选条件支持模糊匹配
       $list=Db::name('content a')->field($fields)
           ->where($scode_arr)
            //->where($where)
			//->where($whereRun)
            //->whereOR($tags)
            ->join('content_sort b','a.scode=b.scode','LEFT')
			->join('content_sort c','a.subscode=c.scode','LEFT')
			->join('model d','b.mcode=d.mcode','LEFT')
			->join('content_ext e','a.id=e.contentid','LEFT')
            ->order($order)
			->paginate($num, false)
			->each(function($item, $key){
				if($item['type']!=1){
					$item['link']=url($item['urlname'],['id'=>$item['id']]);
				}else{
					$item['link']=url($item['urlname'],['tid'=>$item['scode']]);
				}
				return $item;
			});
			//$list =$list->items();
			/*foreach($list as $key=>$val){
				if($val['type']!=1){
					$list[$key]['link']=url($val['urlname'],['id'=>$val['id']]);
				}else{
					$list[$key]['link']=url($val['urlname'],['tid'=>$val['scode']]);
				}
			}*/
		return $list;
    }

    // 列表内容，不带分页，不区分语言，兼容跨语言
    public function getList($scode, $num, $order,$other='', $start = 1,$tags = array())
    {
        $fields = array(
            'a.*',
            'b.name as sortname',
            'b.filename as sortfilename',
            'c.name as subsortname',
            'c.filename as subfilename',
            'd.type',
            'd.name as modelname',
            'd.urlname',
            'e.*'
        );
		if($start<=0){
			$start=1;
		}

        $scode_arr = array();
        if ($scode) {
            // 获取所有子类分类编码
            $this->scodes = array(); // 先清空
            $arr = explode(',', $scode); // 传递有多个分类时进行遍历
            foreach ($arr as $value) {
                $scodes = $this->getSubScodes(trim($value));
            }
            // 拼接条件
			if($scodes){
				$scode_arr = "a.scode in (" . implode_quot(',', $scodes) . ")";
			}else{
				$scode_arr = "a.subscode=".$scode."";
			}
        }
       if(!empty($other)){
			$where = "a.status=1 and ".$other;
		}else{
			$where = "a.status=1 ";
		}

        // 筛选条件支持模糊匹配
       $list=Db::name('content a')->field($fields)
            ->where($scode_arr)
            ->where($where)
            //->whereOR($tags)
            ->join('content_sort b','a.scode=b.scode','LEFT')
			->join('content_sort c','a.subscode=c.scode','LEFT')
			->join('model d','b.mcode=d.mcode','LEFT')
			->join('content_ext e','a.id=e.contentid','LEFT')
            ->order($order)
            ->limit($start - 1, $num)
            ->select();
			foreach($list as $key=>$val){
				if($val['type']!=1){
					$list[$key]['link']=url($val['urlname'],['id'=>$val['id']]);
				}else{
					$list[$key]['link']=url($val['urlname'],['tid'=>$val['scode']]);
				}
			}
		return  $list;
    }

    // 内容详情，不区分语言，兼容跨语言
    public function getContent($id)
    {
        $field = array(
            'a.*',
            'b.name as sortname',
            'b.filename as sortfilename',
            'b.outlink as sortoutlink',
            'c.name as subsortname',
            'c.filename as subfilename',
            'd.type',
            'd.name as modelname',
            'd.urlname',
            'e.*'
        );
        $result = Db::name('content a')->field($field)
            ->where("a.id='$id'")
            ->where('a.status=1')
            ->join('content_sort b','a.scode=b.scode','LEFT')
			->join('content_sort c','a.subscode=c.scode','LEFT')
			->join('model d','b.mcode=d.mcode','LEFT')
			->join('content_ext e','a.id=e.contentid','LEFT')
            ->find();
		//echo  Db::name('content a')->getlastsql();
		//die;
		if($result['type']!='1'){
			$result['link']=url($result['urlname'],['id'=>$result['id']]);
		}else{
			$result['link']=url($result['urlname'],['tid'=>$result['scode']]);
		}
        return $result;
    }

	 // 内容详情，不区分语言，兼容跨语言
    public function getContentExt($id,$field)
    {
		$result = Db::name('content_ext')
				->where('contentid='.$id)
				->value($field);
        return $result;
    }

    // 单篇详情,不区分语言，兼容跨语言
    public function getAbout($scode)
    {
        $field = array(
            'a.*',
            'b.name as sortname',
            'b.filename as sortfilename',
            'c.name as subsortname',
            'c.filename as subfilename',
            'd.type',
            'd.name as modelname',
            'd.urlname',
            'e.*'
        );
        $result = Db::name('content a')->field($field)
            ->where("a.scode='$scode' OR b.filename='$scode'")
            ->where('a.status=1')
            ->join('content_sort b','a.scode=b.scode','LEFT')
			->join('content_sort c','a.subscode=c.scode','LEFT')
			->join('model d','b.mcode=d.mcode','LEFT')
			->join('content_ext e','a.id=e.contentid','LEFT')
            ->order('id DESC')
            ->find();
		if($result['type']!='1'){
			$result['link']=url($result['urlname'],['id'=>$result['id']]);
		}else{
			$result['link']=url($result['urlname'],['tid'=>$result['scode']]);
		}
        return $result;
    }

    // 指定内容多图,不区分语言，兼容跨语言
    public function getContentPics($id)
    {
        $result = Db::name('content')->where("id='$id'")
            ->where('status=1')
            ->value('pics');
        return $result;
    }

    // 指定内容多选调用
    public function getContentCheckbox($id, $field)
    {
        $result = Db::name('content_ext')->where("contentid='$id'")->value($field);
        return $result;
    }

    // 指定内容标签调用
    public function getContentTags($id)
    {
        $result = Db::name('content')->field('scode,tags')
            ->where("id='$id'")
            ->find();
        return $result;
    }

    // 指定分类标签调用
    public function getSortTags($scode)
    {
        $join = array(
            array(
                'cb_content_sort b',
                'a.scode=b.scode',
                'LEFT'
            ),
            array(
                'ay_model c',
                'b.mcode=c.mcode',
                'LEFT'
            )
        );

        $scode_arr = array();
        if ($scode) {
            // 获取所有子类分类编码
            $this->scodes = array(); // 先清空
            $scodes = $this->getSubScodes(trim($scode)); // 获取子类

            // 拼接条件
            $scode_arr = array(
                "a.scode in (" . implode_quot(',', $scodes) . ")",
                "a.subscode='$scode'"
            );
        }

        $result = Db::name('content a')->where("c.type=2 AND a.tags<>''")
            ->where($scode_arr, 'OR')
            ->join($join)
            ->order('a.visits DESC')
            ->column('a.tags');
        return $result;
    }

    // 上一篇内容
    public function getContentPre($scode, $id)
    {
		$data = array();
		$this->scodes = array();
		$scodes = $this->getSubScodes($scode);
		$field = array(
			'a.id',
			'a.title',
			'a.filename',
			'a.ico',
			'a.scode',
			'b.filename as sortfilename',
			'c.type',
			'c.urlname'
		);
		$data = Db::name('content a')
			->field($field)
			->where("a.id<$id")
			->join('content_sort b','a.scode=b.scode','LEFT')
			->join('model c','b.mcode=c.mcode','LEFT')
			->where('a.scode','in', $scodes)
			->where('a.status=1')
			->order('a.id DESC')
			->find();

		if(is_array($data) && !empty($data)){
			if($data['type']!=1){
				$data['link']=url($data['urlname'],['id'=>$data['id']]);
			}else{
				$data['link']=url($data['urlname'],['tid'=>$data['scode']]);
			}
		}
        return $data;
    }

    // 下一篇内容
    public function getContentNext($scode, $id)
    {
		$data = array();
		$this->scodes = array();
		$scodes = $this->getSubScodes($scode);

		$field = array(
			'a.id',
			'a.title',
			'a.filename',
			'a.ico',
			'a.scode',
			'b.filename as sortfilename',
			'c.type',
			'c.urlname'
		);
		$data = Db::name('content a')->field($field)
			->where("a.id>$id")
			->join('content_sort b','a.scode=b.scode','LEFT')
			->join('model c','b.mcode=c.mcode','LEFT')
			->where('a.scode','in', $scodes)
			->where('a.status=1')
			->order('a.id ASC')
			->find();
		if(is_array($data) && !empty($data)){
			if($data['type']!='1'){
				$data['link']=url($data['urlname'],['id'=>$data['id']]);
			}else{
				$data['link']=url($data['urlname'],['tid'=>$data['scode']]);
			}
		}
        return $data;
    }

    // 幻灯片
    public function getSlides($gid, $num, $start = 1)
    {
        $result = Db::name('slide')->where("gid='$gid'")
            ->order('sorting ASC,id ASC')
            ->limit($start - 1, $num)
            ->select();
        return $result;
    }

    // 友情链接
    public function getLinks($gid, $num, $start = 1)
    {
        $result = Db::name('link')->where("gid='$gid'")
            ->order('sorting ASC,id ASC')
            ->limit($start - 1, $num)
            ->select();
        return $result;
    }

    // 获取留言
    public function getMessage($num, $page = true, $start = 1, $lg = null)
    {
        if ($lg == 'all') {
            $where = array();
        } elseif ($lg) {
            $where = array(
                'acode' => $lg
            );
        } else {
            $where = array(
                'acode' => get_lg()
            );
        }
        if ($page) {
            return Db::name('message')->where("status=1")
                ->where($where)
                ->order('id DESC')
                ->decode(false)
                ->page(1, $num, $start)
                ->select();
        } else {
            return Db::name('message')->where("status=1")
                ->where($where)
                ->order('id DESC')
                ->decode(false)
                ->limit($start - 1, $num)
                ->select();
        }
    }

    // 新增留言
    public function addMessage($data)
    {
        return Db::name('message')->insert($data);
    }

    // 获取表单字段
    public function getFormField($fcode)
    {
        $field = array(
            'a.table_name',
            'a.form_name',
            'b.name',
            'b.required',
            'b.description'
        );

        $join = array(
            'ay_form_field b',
            'a.fcode=b.fcode',
            'LEFT'
        );

        return Db::name('form a')->field($field)
            ->where("a.fcode='$fcode'")
            ->join($join)
            ->order('b.sorting ASC,b.id ASC')
            ->select();
    }

    // 获取表单表名称
    public function getFormTable($fcode)
    {
        return Db::name('form')->where("fcode='$fcode'")->value('table_name');
    }

    // 获取表单数据
    public function getForm($table, $num, $page = true, $start = 1)
    {
        if ($page) {
            return Db::table($table)->order('id DESC')
                ->decode(false)
                ->page(1, $num, $start)
                ->select();
        } else {
            return Db::table($table)->order('id DESC')
                ->decode(false)
                ->limit($start - 1, $num)
                ->select();
        }
    }

    // 新增表单数据
    public function addForm($table, $data)
    {
        return Db::table($table)->insert($data);
    }

    // 文章内链
    public function getTags()
    {
        return Db::name('tags')->field('name,link')
            ->where("acode='" . get_lg() . "'")
            ->order('length(name) desc')
            ->select();
    }
		/**
	* 将16进制颜色转换为RGB
	*/
	public function hex2rgb(){
		$data = $this->getSite();
		 $color=str_replace('#','',$data['themese']);
		 if (strlen($color)> 3){
			 /*$rgb=array(
			  'r'=>hexdec(substr($color,0,2)),
			  'g'=>hexdec(substr($color,2,2)),
			  'b'=>hexdec(substr($color,4,2))
			 );*/
			 $rgb=hexdec(substr($color,0,2)).','.hexdec(substr($color,2,2)).','.hexdec(substr($color,4,2));
		 }else{
			 $r=substr($color,0,1). substr($color,0,1);
			 $g=substr($color,1,1). substr($color,1,1);
			 $b=substr($color,2,1). substr($color,2,1);
			 $rgb=hexdec($r).','.hexdec($g).','.hexdec($b);
			 /*$rgb=array(
			  'r'=>hexdec($r),
			  'g'=>hexdec($g),
			  'b'=>hexdec($b)
			 );*/
		 }
		 return $rgb;
	}
	// 获取顶级栏目信息
    public function getTSortinfo($scode)
    {
        $result = $this->getSortList_qd();
        return $result[$scode];
    }
	// 获取顶级栏目信息
    public function getSortinfo($scode)
    {
		$fields = array(
                'a.id',
                'a.pcode',
                'a.scode',
				'a.ico',
				'a.pic',
				'a.mcode',
				'a.keywords',
				'a.description',
                'a.name'
            );
		$result = Db::name('content_sort a')
				->field($fields)
				->where('scode='.$scode)
				->find();
        return $result;
    }
	// 获取顶级栏目信息
    public function getcontentfield($id,$field)
    {
		$result = Db::name('content')
				->where('id='.$id)
				//->join('content_ext e','a.id=e.contentid','LEFT')
				->value($field);
        return $result;
    }
	//获取全局分类根据父id查询 $TypeID 分类id 或父id,$mcode 模型id,$scode 栏目id
	public function GetWholeType($TypeID,$mcode,$scode=''){
		$fields = array(
			'w.TypeID',
			'w.TypeName',
			'w.TypePID',
			'w.TypeMcode',
			'm.type',
			'm.urlname'
         );
		$Where=array();
		$Where['TypePID']=$TypeID;
		$Where['TypeState']=1;
		$Where['TypeMcode']=$mcode;
		$List=db::name('wholetype w')
			->field($fields)
			->where($Where)
			->join('model m','w.TypeMcode=m.mcode','LEFT')
			->order('w.TypeSort Asc,w.TypeID Asc')
			->select();
		/*foreach($List as $key=>$val){
			if($val['type']!=1){
				$List[$key]['link']=url($val['urlname'].'list',['tid'=>$scode]);
			}
		}*/
		return $List;
	}

	// 获取whole分类字段 id获取
    public function getWholeField($id,$field='TypeName')
    {
		$result = Db::name('wholetype')
				->where('TypeID='.$id)
				->value($field);
        return $result;
    }
}